const db = require('./backend/config/db');

async function testQueries() {
  try {
    console.log('=== 测试用户查询 ===');
    const sql1 = `
      SELECT 
        id, username, email, phone, avatar,
        CASE WHEN is_admin = 1 THEN 'admin' ELSE 'user' END as role,
        created_at
      FROM jd_users
      WHERE 1=1
      ORDER BY created_at DESC LIMIT 10 OFFSET 0
    `;
    
    const [users] = await db.execute(sql1, []);
    console.log(`成功查询到 ${users.length} 个用户`);
    if (users.length > 0) {
      console.log('第一个用户:', users[0]);
    }

    console.log('\n=== 测试订单查询 ===');
    const sql2 = `
      SELECT 
        o.id, o.order_no, o.user_id, o.total_amount, o.actual_amount,
        o.status, o.receiver_address, o.created_at, o.updated_at,
        u.username
      FROM jd_orders o
      LEFT JOIN jd_users u ON o.user_id = u.id
      WHERE 1=1
      ORDER BY o.created_at DESC LIMIT 10 OFFSET 0
    `;
    
    const [orders] = await db.execute(sql2, []);
    console.log(`成功查询到 ${orders.length} 个订单`);
    if (orders.length > 0) {
      console.log('第一个订单:', orders[0]);
    }

    console.log('\n=== 测试COUNT查询 ===');
    const countSql = `SELECT COUNT(*) as total FROM jd_users WHERE 1=1`;
    const [countResult] = await db.execute(countSql, []);
    console.log('用户总数:', countResult[0].total);

    console.log('\n=== 测试正则替换后的COUNT查询 ===');
    const originalSql = `
      SELECT 
        id, username, email, phone, avatar,
        CASE WHEN is_admin = 1 THEN 'admin' ELSE 'user' END as role,
        created_at
      FROM jd_users
      WHERE 1=1
    `;
    const replacedCountSql = originalSql.replace(/SELECT[\s\S]*?FROM/, 'SELECT COUNT(*) as total FROM');
    console.log('替换后的SQL:', replacedCountSql);
    const [countResult2] = await db.execute(replacedCountSql, []);
    console.log('用户总数:', countResult2[0].total);

  } catch (error) {
    console.error('错误:', error.message);
    console.error('堆栈:', error.stack);
  } finally {
    process.exit(0);
  }
}

testQueries();

